package com.think.admin.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.think.admin.annotations.MenuAnnotation;
import com.think.admin.annotations.ResourceAnnotation;
import com.think.admin.cons.AdminCons;
import com.think.admin.model.dto.role.RoleDTO;
import com.think.admin.model.dto.role.RoleSysUserDTO;
import com.think.admin.model.param.role.RoleParam;
import com.think.admin.model.param.role.SetRoleResourceParam;
import com.think.admin.model.query.RoleQuery;
import com.think.admin.oauth.util.OAuthUtil;
import com.think.admin.web.service.IRoleService;
import com.think.admin.web.service.IUserRoleService;
import com.think.common.enums.StateEnum;
import com.think.common.enums.SysUserTypeEnum;
import com.think.common.param.UpdateBatchParam;
import com.think.common.utils.ResultUtil;
import com.think.common.utils.SysUtils;
import com.think.common.validation.CreateOrUpdate;
import com.think.common.validation.Update;
import com.think.common.web.controller.SuperController;
import com.think.dao.entity.Role;
import com.think.dao.entity.UserRole;
import com.think.dao.enums.ResourcePermissionTypeEnum;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.http.HttpEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色
 * </p>
 *
 * @author xwj
 * @date 2019/4/25
 */
@RestController
@RequestMapping(value = "admin/role")
@RequiredArgsConstructor
@MenuAnnotation(name = "角色管理", sort = 2, permissionType = ResourcePermissionTypeEnum.PERMISSION)
public class RoleController extends SuperController {
    private final IRoleService roleService;
    private final IUserRoleService userRoleService;
    private final RedissonClient redissonClient;

    @GetMapping
    @ResourceAnnotation(name = "查看", sort = 1, permissionType = ResourcePermissionTypeEnum.PERMISSION)
    public HttpEntity<IPage<RoleDTO>> page(RoleQuery roleQuery) {
        return roleService.selectPage(getPage(), roleQuery);
    }

    @PostMapping
    @ResourceAnnotation(name = "新增修改", sort = 2, permissionType = ResourcePermissionTypeEnum.PERMISSION)
    public HttpEntity createOrUpdate(@RequestBody @Validated(CreateOrUpdate.class) RoleParam roleParam) {
        return roleService.createOrUpdate(roleParam);
    }

    @PostMapping("/batch-delete")
    @ResourceAnnotation(name = "删除", sort = 3, permissionType = ResourcePermissionTypeEnum.PERMISSION)
    public HttpEntity delete(@RequestBody List<String> idList) {
        return roleService.delete(idList);
    }

    @PutMapping("/batch-updateState")
    @ResourceAnnotation(name = "启用禁用", sort = 4, permissionType = ResourcePermissionTypeEnum.PERMISSION)
    public HttpEntity updateState(@RequestBody @Validated(Update.class) UpdateBatchParam updateBatchParam) {
        return roleService.updateState(updateBatchParam);
    }

    @PutMapping("/setRoleResource")
    @ResourceAnnotation(name = "角色菜单", sort = 5, permissionType = ResourcePermissionTypeEnum.PERMISSION)
    public HttpEntity updateState(@RequestBody @Validated(Update.class) SetRoleResourceParam setRoleResourceParam) {
        return roleService.setRoleResource(setRoleResourceParam);
    }

    @GetMapping("/{id}")
    @ResourceAnnotation(name = "角色详情", sort = 6, permissionType = ResourcePermissionTypeEnum.LOGIN)
    public HttpEntity get(@PathVariable("id") String id) {
        // 根据id查询
        Role role = roleService.getById(id);
        if (SysUtils.isEmpty(role)) {
            return ResultUtil.getError();
        }

        // 返回
        return ResultUtil.success(role);
    }

    @GetMapping("/all")
    @ResourceAnnotation(name = "角色分配列表", sort = 6, permissionType = ResourcePermissionTypeEnum.LOGIN)
    public HttpEntity all(String userId) {

        // 查询可分配的角色
        List<Role> roleList;
        //所有的角色
        List<Role> allRoleList = roleService.lambdaQuery()
                .select(Role::getId, Role::getRoleName)
                .eq(Role::getState, StateEnum.ENABLE).list();
        if (AdminCons.Param.SUPER_ADMIN_ID.equals(OAuthUtil.getUserId())) {
            // 管理员，直接从数据库获取资源
            roleList = allRoleList;
        } else {
            roleList = new ArrayList<>();
            String flag = "";
            // 非管理员，用户的角色
            //老板角色
            if(OAuthUtil.getUser().getType().equals(SysUserTypeEnum.SUPER_ADMIN)){
                for(Role rolePO:allRoleList){
                    if(!"14".equals(rolePO.getId().toString())){
                        roleList.add(rolePO);
                    }
                }
            }
            //销售经理 和 渠道经理
            if(SysUserTypeEnum.SALESMANAGER.equals(OAuthUtil.getUser().getType()) || SysUserTypeEnum.CHANNELMANAGER.equals(OAuthUtil.getUser().getType())){
                for(Role rolePO:allRoleList){
                    if("18".equals(rolePO.getId().toString()) || "21".equals(rolePO.getId().toString())){
                        roleList.add(rolePO);
                    }
                }
            }
            //销售总监
            if(SysUserTypeEnum.DIRECTOROFSALES.equals(OAuthUtil.getUser().getType())){
                for(Role rolePO:allRoleList){
                    if(!"14".equals(rolePO.getId().toString()) && !"19".equals(rolePO.getId().toString())){
                        roleList.add(rolePO);
                    }
                }
            }
        }

        // 获取传入用户所拥有的角色
        List<String> haveRoleIdList;
        if (SysUtils.isNotEmpty(userId)) {
            haveRoleIdList = userRoleService.lambdaQuery()
                    .select(UserRole::getRoleId).eq(UserRole::getUserId, userId)
                    .list().stream()
                    .filter(SysUtils::isNotEmpty).map(UserRole::getRoleId).collect(Collectors.toList());
        } else {
            haveRoleIdList = new ArrayList<>();
        }

        // 构造返回数据
        List<RoleSysUserDTO> roleSysUserDTOList = new ArrayList<>();
        roleList.forEach(role -> {
            RoleSysUserDTO roleSysUserDTO = new RoleSysUserDTO();
            roleSysUserDTO.setRoleId(role.getId());
            roleSysUserDTO.setRoleName(role.getRoleName());
            if (SysUtils.isNotEmpty(haveRoleIdList) && haveRoleIdList.contains(role.getId())) {
                roleSysUserDTO.setChecked(true);
            } else {
                roleSysUserDTO.setChecked(false);
            }
            roleSysUserDTOList.add(roleSysUserDTO);
        });

        // 返回
        return ResultUtil.success(roleSysUserDTOList);
    }
}
